package com.web.nyist.interceptor;

import com.web.nyist.common.Constant;
import com.web.nyist.dto.admin.AdminUserDto;
import com.web.nyist.service.HtmlService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 后台管理登入拦截器，判断session中是否用户存在，如果不存在调整到登入页面
 * Created by penghuiping on 3/17/15.
 */
@Component
public class AdminLoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    HtmlService htmlService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AdminUserDto user = (AdminUserDto) request.getSession().getAttribute(Constant.SESSION_USER);
        if (null == user) {
            PrintWriter printWriter = response.getWriter();
            printWriter.write("<script>window.parent.location.href = \"" + htmlService.getBasePath(request) + "/admin/common/login.do\";</script>");
            printWriter.flush();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (null != modelAndView) {
            AdminUserDto user = (AdminUserDto) request.getSession().getAttribute(Constant.SESSION_USER);
            //menu
            modelAndView.addObject("menus", user.getMenus());
            modelAndView.addObject("sessionUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }


}
